﻿/*文件注释
 * ===============================================================================
 * 说明：
 * 作者：曾永佑
 * 版本：V1.0
 * 创建日期：2013-02-10
 * 完成日期： 
 * 修改纪录：  
 * ===============================================================================
 */  
        
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SRF.Data.Impl
{
    public class SqlDatabase : Database
    {
        public SqlDatabase(string connectionString)
            : base(connectionString, System.Data.SqlClient.SqlClientFactory.Instance)
        {
        }

        public override string BuildPageSql(string sql, int startRow, int? maxRows, string orderBy = "")
        {
            sql = sql.Trim();
            int orderbyIndex = sql.LastIndexOf("order", StringComparison.OrdinalIgnoreCase);
            if (orderbyIndex == -1 && string.IsNullOrEmpty(orderBy))
            {
                throw new ArgumentException("sql语句必须包含order by");
            }
            else
            {
                if (!string.IsNullOrEmpty(orderBy))
                {
                    orderBy = "order by " + orderBy;
                }
                else
                {
                    orderBy = sql.Substring(orderbyIndex);
                }
                if (orderbyIndex > -1)
                    sql = sql.Substring(0, orderbyIndex);
                System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("^select", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                sql = regex.Replace(sql, "select row_number() over(" + orderBy + ") as __row,");
                sql = string.Format("select {0} * from ({1}) as _table where _table.__row>={2}", maxRows == null ? "" : "top " + maxRows.Value.ToString(), sql, startRow);
            }

            return sql;
        }

        public override char ParameterToken
        {
            get { return '@'; }
        }
        public virtual char CloseQuote
        {
            get { return ']'; }
        }
        public virtual char OpenQuote
        {
            get { return '['; }
        }
    }
}